# -*- coding: utf-8 -*-

'''eof
name:近半年负面舆情高风险企业数与该行业上市发债企业企业总数占比
code:Industry_Score_5
tableName:
columnName:
groups:行业评分模块
dependencies:INDUSTRY_INFO
type:常用指标
datasourceType:在线指标
description:
eof'''
from __future__ import division
from dateutil.relativedelta import relativedelta
from dateutil.parser import parse
import datetime
import pandas as pd


null_type_list = ['', None, 'None', 'null', 'Null', 'NULL', '/', ' ',[]]

def timeCompare2(a,time):
    List = list(a)
    error = 0
    result = []
    for i in List:
        try:
            if parse(i).date() == time:
                result.append(True)
            else:
                result.append(False)
        except:
            error += 1
            result.append(False)
    if len(List) == error:
        raise RuntimeError(u"日期字段解析全部失败") 
    return result


def Industry_Score_5():
    data = INDUSTRY_INFO.get("data")
    if data in null_type_list:
        return u"缺失值"
    else:
        #计算factor1
        industryNewsStatistic = data.get("industryNewsStatistic")
        if industryNewsStatistic in null_type_list:
            return u"缺失值"
        else:
            DATA = pd.DataFrame(industryNewsStatistic)
            timeList = []
            timeError = 0
            for i in DATA["statisticsDate"]:
                try:
                    timeList.append(parse(i).date())
                except:
                    timeError += 1
            if timeError == len(DATA):
                raise RuntimeError(u"统计日期字段解析全部失败") 
            timeMax = max(timeList)
            DATA = DATA[pd.Series(timeCompare2(DATA["statisticsDate"],timeMax),index=DATA.index)].reset_index(drop=True)
            try:
                factor1 = int(DATA["reverseHigh"][0])
            except:
                factor1 = u"缺失值"
            
        #计算factor2
        statisticIndicatorData = data.get("statisticIndicatorData")
        if statisticIndicatorData in null_type_list:
            factor2 = 0
        else:
            DATA = pd.DataFrame(statisticIndicatorData)
            DATA = DATA[DATA["indicatorName"] == u"上市或发债企业数量"]
            if len(DATA) != 0:        
                timeList2 = []
                timeError2 = 0
                for i in DATA["statisticsDate"]:
                    try:
                        timeList2.append(parse(i).date())
                    except:
                        timeError2 += 1
                if timeError2 == len(DATA):
                    raise RuntimeError(u"统计日期字段解析全部失败") 
                timeMax2 = max(timeList2)
                DATA = DATA[pd.Series(timeCompare2(DATA["statisticsDate"],timeMax2),index=DATA.index)].reset_index(drop=True)
                try:
                    factor2 = int(DATA["indicatorValue"][0])
                except:
                    factor2 = u"缺失值"
            else:
                factor2 = u"缺失值"
        
        if factor2 in [0,u"缺失值"] and factor1 > 0:
            return 999999
        elif factor2 == 0 and factor1 == 0:
            return 0
        else:
            try:
                return round(factor1/factor2,4)
            except:
                return u"缺失值"

result = Industry_Score_5()
